<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/10/18 16:07
 */

namespace App\Project\Search;

use App\Project\Search\Exception\MedicalRecordSearchException;
use Illuminate\Support\Str;

class Expression
{
    protected $map = [
        'eq' => '=',
        'gt' => '>=',
        'lt' => '<=',
        'bt' => 'between',
        'in' => 'in',
        'ex' => 'ex',
    ];

    /**
     * @var string
     */
    protected $table = '';

    public function eq($field, $value)
    {
        $this->exceptionForValueNumber('eq', count($value), 1);

        return [$this->setTablePrefix($field), '=', $value];
    }

    public function gt($field, $value)
    {
        $this->exceptionForValueNumber('gt', count($value), 1);

        return [$this->setTablePrefix($field), '>=', $value];
    }

    public function lt($field, $value)
    {
        $this->exceptionForValueNumber('lt', count($value), 1);

        return [$this->setTablePrefix($field), '<=', $value];
    }

    public function in($field, $value)
    {
        if (count($value) == 0) {
            return [];
        }

        return [$this->setTablePrefix($field), $value];
    }

    public function ex($field)
    {
        return [$this->setTablePrefix($field)];
    }

    public function bt($field, $value)
    {
        $this->exceptionForValueNumber('bt', count($value), 2);

        return [$this->setTablePrefix($field), $value];
    }

    protected function setTablePrefix($field)
    {
        if (!empty($this->table) && !Str::startsWith($field, $this->table . '.')) {
            $field = '`' . $this->table . '`.' . $field . '';
        }

        return $field;
    }

    protected function exceptionForValueNumber($operator, $count, $need)
    {
        if ($count !== $need) {
            throw new MedicalRecordSearchException($operator . ' 操作符需要 '. $need .'个参数值。');
        }
    }

    /**
     * @param string $table
     * @return $this
     */
    public function setTable($table)
    {
        $this->table = $table;

        return $this;
    }
}